package com.aos.controller;

import com.aos.exception.BusinessException;
import com.aos.exception.ResultStatus;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.web.bind.annotation.*;

@RestController
@Api(value = "OAuth Controller", tags = {"OAuth2接口"})
public class OAuthController {
    //Redis配置
    @Autowired
    private RedisConnectionFactory connectionFactory;

    //Redis存储
    @Bean
    public TokenStore tokenStore() {
        RedisTokenStore redis = new RedisTokenStore(connectionFactory);
        return redis;
    }

    /**
     * 用户登出并注销 Token
     * @param {String} access_token
     * @return String
     */
    @ApiOperation(value = "注销用户 Token", notes = "注销用户 Token")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access_token", value = "令牌",   required = true,paramType = "query", dataType = "String")
    })
    @RequestMapping(value = "/oauth/revoke-token", method = RequestMethod.POST)
    //@ResponseStatus(HttpStatus.OK)
    public String logout(@RequestParam("access_token") String access_token) {
        System.out.println("===============开始注销===============");
        System.out.println("========access_token:" + access_token);
        if(access_token.trim().equals(""))
        {
            throw new BusinessException("无效的token！", ResultStatus.fail.toString());
        }
        OAuth2AccessToken accessToken = tokenStore().readAccessToken(access_token);
        tokenStore().removeAccessToken(accessToken);
        return "注销成功！";
    }
}
